home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10037 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  68 lines

  1. Newsgroups: comp.lang.c
  2. Path: alisa.org!wjjr
  3. From: wjjr@alisa.org (John J. Rushford)
  4. Subject: Re: hex to dec function?
  5. X-Newsreader: TIN [version 1.2 PL2]
  6. Organization: My place on the Front Range.
  7. Message-ID: <DoAE6F.2CD@alisa.org>
  8. References: <4gdh1b$bg@mailhost.mwmicro.com> <4hl8mk$1er@info.uah.edu> <313EE885.4511@cmt.lpr.mail.carel.fi> <4i87sm$7n0@info.uah.edu>
  9. Date: Fri, 15 Mar 1996 02:13:27 GMT
  10.  
  11. Greg Bacon (gbacon@oreo) wrote:
  12. : Ari Lukumies (aril@cmt.lpr.mail.carel.fi) wrote:
  13. : : Greg Bacon wrote:
  14. : : > 
  15.  
  16. : : [snip]
  17.  
  18. : : > Assuming you have a string representing some hexadecimal quantity and
  19. : : > you want to print its equivalent decimal value:
  20. : : > 
  21. : : > #include <stdio.h>
  22. : : > #include <stdlib.h>
  23. : : > 
  24. : : > /*
  25. : : >  :
  26. : : >  :
  27. : : >  */
  28. : : > {
  29. : : >    char *strHexVal = "20";  /* 32 auf decimal */
  30. : : > 
  31. : : >    (void) printf("%d\n", strtol(strHexVal, (char **) NULL, 10));
  32. : : > [snip]
  33.  
  34. : : Just a quick sidenote: if you use strtol() in a printf call, use the
  35. : : correct format string, also: "%ld\n".
  36.  
  37. : : Later,
  38. : :  AriL
  39.  
  40. : OK, OK.. you got me.  I should have commented that I was assuming int
  41. : and long were of the same length (a trait not often found on the
  42. : braindead iAPX platform :).
  43.  
  44. : The above works on most modern Unices.
  45.  
  46. It didn't work on mine and why should it?  How does strtol know that "20" is
  47. base 16?  The following, Is what I think you were trying to convey:
  48.  
  49.     char *strHexVal = "0x20";  /* 32 auf decimal */
  50.  
  51.     printf ("%d\n", strtol (strHexVal, (char **) NULL, 16));
  52.                                ^^^
  53.                                not 10
  54.  
  55. The following works too: 
  56.  
  57.     char *strHexVal = "20";
  58.  
  59.     printf("%d\n",((((atol(strHexVal)) / 10) * 16) + ((atol(strHexVal) % 10))));
  60.  
  61.  
  62. regards
  63. -- 
  64. John J. Rushford              
  65. Westminster, Colorado___/\_/\_
  66. wjjr@alisa.org (alisa.org is powered by FreeBSD)
  67.  
  68.